package com.work.servlet.teacher;

import com.work.bean.Work;
import com.work.service.WorkService;
import com.work.service.impl.WorkServiceImpl;
import com.work.utils.Office2Swf;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/10/6.
 */
@WebServlet("/upload_work")
public class WorkServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = request.getSession();

        if (session.getAttribute("isLogin") != null && (Boolean) session.getAttribute("isLogin")) {

            String end = null;
            request.setCharacterEncoding("utf-8");    //设置编码
            //获得磁盘文件条目工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //获取文件需要上传到的路径
            String path = request.getServletContext().getRealPath("/upload");

            System.out.println(path + "-------path-");

            factory.setRepository(new File(path));
            //设置 缓存的大小，当上传文件的容量超过该缓存时，直接放到 暂时存储室
            factory.setSizeThreshold(1024 * 1024 * 5);
            //高水平的API文件上传处理
            ServletFileUpload upload = new ServletFileUpload(factory);

            String uploadFilePath = null;
            String filename = null;
            //可以上传多个文件
            try {
                List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
                for (FileItem item : list) {
                    //获取表单的属性名字
                    String name = item.getFieldName();

                    // 表单文本信息
                    if (item.isFormField()) {
                        end = item.getString();
                        end = end.replace("T", " ");
                        session.setAttribute(name, end);
                    }
                    // 表单上传的文件
                    else {
                        // 获取路径
                        String value = item.getName();

                        System.out.println(value + "--value---");

                        int start = value.lastIndexOf("\\");
                        // 截取 上传文件名称
                        filename = value.substring(start + 1);

                        System.out.println(filename + "--filename---");

                        session.setAttribute(name, filename);

                        item.write(new File(path, filename));


                        uploadFilePath = path + File.separator + filename;

                        session.setAttribute("uploadFilePath", uploadFilePath);
                        System.out.println(uploadFilePath + "---uploadFilePath--");

                    }
                }

                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Date date = new Date();

                WorkService service = new WorkServiceImpl();

                String inputFilePath = uploadFilePath;
                String readOnlinePath = null;


                System.out.println(inputFilePath+"555-----");

                if (null != inputFilePath && !"".equals(inputFilePath.trim()))
                {
                    String outFilePath = inputFilePath.replace(new File(inputFilePath).getName(), System.currentTimeMillis() + ".swf");
                    outFilePath = Office2Swf.office2Swf(inputFilePath, outFilePath);
                    readOnlinePath = new File(outFilePath).getName();
//                    session.setAttribute("fileName", new File(outFilePath).getName());
                }

                service.insertWork(new Work((Integer) session.getAttribute("teacherId"), uploadFilePath,readOnlinePath,filename,format.format(date), end));
                resp.sendRedirect("/history_work");

            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else {
            session.setAttribute("error", "请登录后访问");
            resp.sendRedirect("login.jsp");
        }


    }
}
